<template>
  <div>
    <a-modal
      :visible="visible"
      @cancel="handleCancel"
      ok-text="提交"
      cancel-text="取消"
      title="事件处理"
      title-align="start"
      unmount-on-close
    >
      <a-form
        :model="formValue"
        layout="vertical"
        size="large"
        ref="formRef"
      >
        <a-form-item
          field="process_msg"
          label="处理备注"
        >
          <a-textarea
            v-model="formValue.process_msg"
            placeholder="请填写处理备注"
            allow-clear
            :max-length="200"
            show-word-limit
            :auto-size="{ minRows: 4, maxRows: 4 }"
          />
        </a-form-item>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="handleCancel">取消</a-button>
          <a-divider direction="vertical" />
          <a-button @click="submit('DEPRECATED')">不符合条件</a-button>
          <a-button @click="submit('FAILED')">调解不成</a-button>
          <a-button @click="submit('WITHDRAW')">自行和解</a-button>
          <a-button type="primary" @click="submit('COMPLETED')">达成协议</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { watch, ref } from 'vue'
import { cloneDeep } from 'lodash-es'
import { useRoute } from 'vue-router'

import { useApi } from '/@/api'
import { noop } from '/@/utils/helper'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  onClose: {
    type: Function,
    default: () => noop
  }
})
const visible = ref(false)

const route = useRoute()

const formRef = ref()
const formInitValue = {
  process_msg: null
}
const formValue = ref(cloneDeep(formInitValue))

watch(
  () => props.visible,
  v => {
    visible.value = v
  }, { immediate: true })

function handleCancel() {
  if (formRef.value?.resetFields) {
    formRef.value?.resetFields()
  }
  formValue.value = cloneDeep(formInitValue)
  props.onClose()
  visible.value = false
}

function submit(status) {
  const values = { status }

  if (formValue.value.process_msg !== null) {
    values.process_msg = formValue.value.process_msg
  }

  useApi()
    .post(
      `ticket/${route.params.id}/update`,
      values, { authorize: true }
    )
    .then(res => {
      if (res.code === 0) {
        handleCancel()
      }
    })
}
</script>